import React from 'react';
import {Modal} from 'antd';
import _ from 'lodash';
import Table, {
    setColumnKeys,
    yesRender
} from '../_/table';
export default class EitorSelDepartment extends React.Component {
    state = {selectedRowKeys: [], selectedRows: []}

    componentWillReceiveProps(props) {
        const {ids} = props;
        const {ids: o} = this.props;
        if (ids !== o) {
            this.reset();
        }
    }

    onOk = () => {
        const {selectedRows} = this.state;
        const sels = _.map(selectedRows, i => i.Id);
        this.props.onState('selDepartmentOk', sels);
        this.reset();
    }

    onCancel = () => {
        this.reset();
        this.props.onState('selDepartmentCancel');
    }

    onRowSelection = (r, i) => {
        const {selectedRowKeys, selectedRows} = this.state;
        if (_.indexOf(selectedRowKeys, i) >= 0) {
            _.pull(selectedRowKeys, i);
            _.pull(selectedRows, r);
        } else {
            selectedRowKeys.push(i);
            selectedRows.push(r);
        }
        this.setState({selectedRowKeys, selectedRows});
    }

    reset = () => this.setState({selectedRowKeys: [], selectedRows: []});

    render() {
        const {data, ids} = this.props;
        const dataSource = _.filter(data, i => i.Status && !_.some(ids, k => k === i.Id));
        const columns = [{
            title: '编码',
            dataIndex: 'Code'
        }, {
            title: '名称',
            dataIndex: 'Name'
        }, {
            title: '状态',
            dataIndex: 'Status',
            render: yesRender
        }];
        setColumnKeys(columns);
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({selectedRowKeys, selectedRows});
            },
        };

        return (
            <div>
                <Modal
                    width={this.props.width}
                    title="添加科室"
                    okText="添加"
                    maskClosable={false}
                    onOk={this.onOk}
                    onCancel={this.onCancel}
                    wrapClassName={`editorSelDepartmenModal`}
                    visible={this.props.visible}
                >
                    <Table
                        size="small"
                        rowSelection={rowSelection}
                        dataSource={dataSource}
                        columns={columns}
                        pagination={false}
                        onRowClick={this.onRowSelection}
                    />
                </Modal>
            </div>
        );
    }
}
